<?php

namespace App\Observers;

use App\Events\LogArticleEvent;
use App\Model\Article;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Request;

class ArticleObserver
{
    /**
     * Handle the article "created" event.
     *
     * @param  \App\Model\Article  $article
     * @return void
     */
    public function created(Article $article)
    {
        $attributes = $article->getAttributes();
        $modelName = get_class($article);
        $title = 'create';
        event(new LogArticleEvent($modelName, $title, $attributes));
    }

    /**
     * Handle the article "updated" event.
     *
     * @param  \App\Model\Article  $article
     * @return void
     */
    public function updated(Article $article)
    {
    }

    public function saving(Article $article){
    }

    /**
     * 监听数据保存后的事件。
     *
     * @param  User $user
     * @return void
     */
    public function saved(Article $article){
        $attributes = $article->getAttributes();
        $modelName = get_class($article);
        $title = 'saved';
        $origin = $article->getOriginal();

        $data = $article->getChanges();
        $change = [];
        if ($data){
            foreach ($data as $k => $v){
                $change[$k] = $origin[$k] . '=>' . $data[$k];
            }
        }
        event(new LogArticleEvent($modelName, $title, $attributes, $change));
    }

    /**
     * Handle the article "deleted" event.
     *
     * @param  \App\Model\Article  $article
     * @return void
     */
    public function deleted(Article $article)
    {
        $attributes = $article->getAttributes();
        $modelName = get_class($article);
        $title = 'delete';
        event(new LogArticleEvent($modelName, $title, $attributes));
    }

    /**
     * Handle the article "restored" event.
     *
     * @param  \App\Model\Article  $article
     * @return void
     */
    public function restored(Article $article)
    {

    }

    /**
     * Handle the article "force deleted" event.
     *
     * @param  \App\Model\Article  $article
     * @return void
     */
    public function forceDeleted(Article $article)
    {
        //
    }
}
